import { Form, Button, Message } from '@alifd/next';
import React, { useEffect, useState } from 'react';
import { ENUMS, FieldsGrid, TitleGrid } from '../../stores/definitions';
import { t } from '@lingui/macro';
import { useStore } from '@/hooks';
import { observer } from 'mobx-react-lite';
import AttachmentPanel from '../AttachmentPanel';
import { observable } from 'mobx';
import DrawerFooter from '@/components/DrawerFooter';

const TaskInfo = ({ task, visible, modal, onCancel, handleUpdate }) => {
  const { ccTaskStore: store } = useStore();
  const [data] = useState(() => observable({}));
  const [isViewMode] = useState(modal[0] === 'viewTask');

  useEffect(() => {
    (async () => {
      const { driverInfo = [] } = task;
      if (visible) {
        const res = await store.getDriverLog(driverInfo);
        const currDriver = store.getDriverInfo(driverInfo);
        const dataTmp = _.cloneDeep(task || {});
        _.assign(dataTmp, { taskLog: res, DRIVER: currDriver, driverInfo: currDriver });
        _.assign(data, { ...toJS(dataTmp) });
      }
    })();
  }, [visible]);

  const handleSubmit = (__, errors) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    handleUpdate?.(toJS(data));
  };

  const handleCancel = () => {
    onCancel?.();
  };

  const handleCopyTrip = async () => {
    try {
      const text = await store._copyTrip(toJS(data));
      await navigator.clipboard.writeText(text);
      Message.success({ content: t`行程已复制！` });
    } catch (err) {
      console.error('行程复制失败: ', err);
    }
  };

  const handleCopyDispatch = async () => {
    try {
      const text = await store._copyDispatch(toJS(data));
      await navigator.clipboard.writeText(text);
      Message.success({ content: t`派车已复制！` });
    } catch (err) {
      console.error('派车复制失败: ', err);
    }
  };

  return (
    <Form
      inline
      isPreview={false}
    >
      <TitleGrid title={(
        <div style={{ display: 'flex', alignItems: 'center' }}>
          {t`基本信息`}
          <Button text type="primary" style={{ marginLeft: 10, fontWeight: 500 }} onClick={handleCopyTrip}>{t`复制行程信息`}</Button>
        </div>
      )}
      />
      <FieldsGrid
        formData={task}
        mode="view"
        fields={['id', 'state', 'taskType', 'crDate', 'startArea', 'orderBaseModel.beginName', 'endArea', 'orderBaseModel.endName', 'orderBaseModel.language', 'cancelTime', 'driverInfo[0].number', 'dispatchRemarks']}
      />
      <TitleGrid title={t`客户资料`} />
      <FieldsGrid
        formData={task}
        mode="view"
        fields={['passengerName', 'subscribeName', 'passengerPhone', 'subscribePhone', 'number', 'flightNumber'].map((n) => `orderBaseModel.${n}`)}
      />
      <TitleGrid title={
        (
          <div style={{ display: 'flex', alignItems: 'center' }}>
            {t`派车信息`}
            {ENUMS._dispatch_states[toJS(data)?.state] && <Button text type="primary" style={{ marginLeft: 10, fontWeight: 500 }} onClick={handleCopyDispatch}>{t`复制派车信息`}</Button>}
          </div>
        )}
      />
      <FieldsGrid
        formData={toJS(data)}
        mode="view"
        fields={['carrierPrice', 'fleetSettlement', 'driverServiceFee', 'driverSettlement', 'carrierCompanyName', 'dispatcherName', 'driverInfo[0].name', 'driverInfo[0].phone', 'taskLog.beginTime', 'taskLog.completeTime', 'driverInfo[0].licenseNo']}
      />
      <TitleGrid title={t`司机录入费用`} />
      <FieldsGrid
        formData={task}
        mode="view"
        fields={['roadFee', 'oilFee', 'partFee', 'repairFee', 'otherFee', 'surchargeExplain', 'addFee'].map((n) => `orderBaseModel.${n}`)}
      />
      <TitleGrid title={t`备注及图片`} />
      <FieldsGrid
        formData={task}
        mode="view"
        fields={['remark', 'dispatchOrderRemarks', 'cancelRemark']}
      />
      <AttachmentPanel state={data} />
      <DrawerFooter>
        <Form.Item>
          {!isViewMode && <Form.Submit type="primary" onClick={handleSubmit}>{t`提交`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </Form.Item>
      </DrawerFooter>
    </Form>
  );
};

export default observer(TaskInfo);
